package com.vimi8.ebb.auth.api;

import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.model.Error;
import com.vimi8.ebb.auth.model.Token;
import com.vimi8.ebb.auth.model.LoginUser;

import com.vimi8.ebb.auth.service.DBClientDetailsService;
import io.swagger.annotations.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.http.OAuth2ErrorHandler;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-12T05:17:54.080Z")

@Controller
public class LoginApiController extends KaptchaExtendImpl implements LoginApi {
    protected Logger logger =  LoggerFactory.getLogger(this.getClass());

    //@Value("${springfox.documentation.swagger.v2.host}")
    private String host="127.0.0.1";
    @Value("${server.contextPath}")
    private String contextPath;
    @Value("${server.port}")
    private String port;

    @Autowired
    private DBClientDetailsService dbClientDetailsService;

    public HttpResponseEntity<Token> loginPost(

@ApiParam(value = "登录所需的用户信息" ,required=true ) @RequestBody LoginUser loginUser
            , HttpServletRequest request
) {
        HttpResponseEntity<String> response=null;
        HttpHeaders responseHttpHeaders=new HttpHeaders();
        responseHttpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Error error=new Error().error("invalid_param").errorDescription("param is empty");
        if(loginUser!=null){
            if ((StringUtils.isEmpty(loginUser.getLoginName()) || StringUtils.isEmpty(loginUser.getLoginSecret()))){
                error.error("invalid_param").errorDescription("invalid username or password");
            } else {
                //未给client_id则,使用默认的default_client_id
                if(StringUtils.isEmpty(loginUser.getClientId())){
                    loginUser.setClientId(dbClientDetailsService.getDefaultClient(loginUser.getLoginName()));
                }
//                //检查用户是否该角色
//                int userIsClient=-1;
//                try {
//                    userIsClient=dbClientDetailsService.getCountClientUser(loginUser.getClientId(),loginUser.getLoginName());
//                    if(userIsClient<=0){
//                        //防止泄露敏感信息
//                        //error.error("invalid_param").errorDescription(loginUser.getLoginName()+" is not "+loginUser.getClientId());
//                        error.error("invalid_param").errorDescription("invalid client id");
//                    }
//                }catch (Exception ex){
//                    error.error("invalid_param").errorDescription(ex.getLocalizedMessage());
//                }
//                //用户是该角色
//                if(userIsClient>0) {
                    ClientDetails clientDetails = null;
                    try {
                        clientDetails = dbClientDetailsService.getClientDetailsByClientId(loginUser.getClientId());
                        if(clientDetails==null){
                            error.error("invalid_user").errorDescription("invalid client id");
                        }
                    } catch (Exception ex) {
                        error.error("invalid_param").errorDescription(ex.getLocalizedMessage());
                    }
                    //检查clienid是否有效
                    if (clientDetails != null) {
                        RestTemplate restTemplate = new RestTemplate();
                        restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
                        HttpHeaders restHeader = new HttpHeaders();
                        restHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
                        restHeader.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
                        restHeader.add("Authorization", "Basic " + getBASE64(clientDetails.getClientId() + ":" + clientDetails.getClientSecret()));
                        String tokenUrl = String.format("/token?grant_type=password&username=%s&password=%s", loginUser.getLoginName(), loginUser.getLoginSecret());
                        tokenUrl = request.getScheme() + "://" + host + ":" + port + contextPath + tokenUrl;
                        HttpEntity<Void> formEntity = new HttpEntity<Void>(restHeader);
                        //logger.debug("---------tokenUrl:--------" + tokenUrl);
                        Token token = restTemplate.postForObject(tokenUrl, formEntity, Token.class);
                        if(StringUtils.isEmpty(token.getOpenid())){
                            error = new Error().error("login error").errorDescription("还没有给你审批权限！");
                            responseHttpHeaders.add("SET-COOKIE", "Authorization="+ ";expire=" + new Date(0) + ";path=/;HttpOnly");
                            return new HttpResponseEntity<>(error, responseHttpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);

                        }
                        token.setClientId(loginUser.getClientId());
                        //logger.debug("---------token:--------" + token);
                        responseHttpHeaders.add("SET-COOKIE", "Authorization=bearer%20" + token.getAccess_token() + ";expire=" + new Date((new Date().getTime()) + token.getExpires_in() * 1000) + ";path=/;HttpOnly");
                        return new HttpResponseEntity<Token>(token, responseHttpHeaders, HttpStatus.OK);
                    }
//                }
            }
        }
        // do some magic!
        return new HttpResponseEntity<Token>(error,HttpStatus.BAD_REQUEST);
    }

    public HttpResponseEntity<Void> loginVerifyCodeJpgGet(HttpServletRequest req, HttpServletResponse resp) {
        Error error=null;
        try {
            super.captcha(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (error!=null){
            return new HttpResponseEntity<Void>(error,HttpStatus.OK);
        }else{
            return new HttpResponseEntity<Void>(HttpStatus.OK);
        }
    }

    // 将 s 进行 BASE64 编码
    public static String getBASE64(String s) {
        if (s == null) return null;
        return Base64Utils.encodeToString(s.getBytes());
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static String getFromBASE64(String s) {
        if (s == null) return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

}
